﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using Shoozla.View;
using Shoozla.DataModel;
using System.IO;
using System.Windows.Forms;
using System.Threading.Tasks;
using Shoozla.DataModel.Helper;
using MahApps.Metro.Controls;


namespace Shoozla.ViewModel
{
    /// <summary>
    /// The ViewModel for the application's main window.
    /// </summary>
    public class MainViewModel : ViewModelBase
    {
      //  public event FolderAddedDelegate FolderAdded;
        public delegate void FolderAddedDelegate(DirectoryInfo folderName);

        #region Constructors

        public MainViewModel(Window view, Window owner) : base (view,owner)
        {           
            base.DisplayName = "Shoozla Main Window";
            CurrentView = App.FolderView;
        }

        #endregion // Constructor

        #region Commands       

        //private RelayCommand _CmdFindTags;
        //public RelayCommand CmdFindTags
        //{
        //    get
        //    {
        //        if (_CmdFindTags == null)
        //        {
        //            _CmdFindTags = new RelayCommand(param => DoCmdFindTags(), param => CanExecuteSearch());
        //        }
        //        return _CmdFindTags;
        //    }
        //}

        private RelayCommand _CmdOptions;
        public RelayCommand CmdOptions
        {
            get
            {
                if (_CmdOptions == null)
                {
                    _CmdOptions = new RelayCommand(param => DoCmdOptions(), param => true);
                }
                return _CmdOptions;
            }
        }

        private RelayCommand _CmdClose;
        public RelayCommand CmdClose
        {
            get
            {
                if (_CmdClose == null)
                {
                    _CmdClose = new RelayCommand(param =>  System.Windows.Application.Current.Shutdown(), param => true);
                }
                return _CmdClose;
            }
        }
    
        private RelayCommand _CmdSave;
        public RelayCommand CmdSave
        {
            get
            {
                if (_CmdSave == null)
                {
                    _CmdSave = new RelayCommand(param => DoCmdSave(), param => {
                        if (!AppModel.IsAppWorking && AppModel.IsCollectionDirty()) return true;
                        else return false;
                        });
                }
                return _CmdSave;
            }
        }

        private RelayCommand _CmdSearch;
        public RelayCommand CmdSearch
        {
            get
            {
                if (_CmdSearch == null)
                {
                    _CmdSearch = new RelayCommand(param => DoCmdSearch(), param => CanExecuteSearch());
                }
                return _CmdSearch;
            }
        }

        private RelayCommand _CmdOpenFolder;
        public RelayCommand CmdOpenFolder
        {
            get
            {
                if (_CmdOpenFolder == null)
                {
                    _CmdOpenFolder = new RelayCommand(param => DoCmdOpenFolder(null), param => CanExecuteUI());
                }
                return _CmdOpenFolder;
            }
        }

        private RelayCommand _CmdAbout;
        public RelayCommand CmdAbout
        {
            get
            {
                if (_CmdAbout == null)
                {
                    _CmdAbout = new RelayCommand(param => DoCmdAbout(), param => { return true; });
                }
                return _CmdAbout;
            }
        }

        private RelayCommand _CmdOpenLog;
        public RelayCommand CmdOpenFLog
        {
            get
            {
                if (_CmdOpenLog == null)
                {
                    _CmdOpenLog = new RelayCommand(param => DoCmdOpenFLog(), param => { return true; });
                }
                return _CmdOpenLog;
            }
        }

        //need here because the static variable is not inside a INotify Interface     
        public String CurrentFolder
        {
            get { return AppModel.ParentFolder == null ? String.Empty : AppModel.ParentFolder.FullName; }
            set { OnPropertyChanged("CurrentFolder"); }//status bar update
        }

        #endregion

        #region Do Commands

        //private void DoCmdFindTags()
        //{
        //    ////start the internet search        
        //    //AppModel.LogEntry("Connecting to " + AppModel.TagsSearcher.AddInName);

        //    ////clean the logging and everything else at each search
        //    //AppModel.NotFoundMp3 = new List<Mp3File>();

        //    //List<Mp3File> selected = AppModel.SelectedSongs.ToList<Mp3File>();
        //    //AppModel.TagsSearcher.Songs = selected;

        //    ////display UI
        //    //AppModel.ProgressOperationQueue.Add(AppModel.TagsSearcher);
        //    //AppModel.StartProgressBarInternal(AppModel.ProgressOperationQueue.ToList<IProgressOperation>());

        //    //AppModel.ShowCoverPreviewWindow(); //display found covers
        //    //show the tags 
        //}

        private void DoCmdOptions()
        {
            new OptionsView().ShowDialog();
        }

        private void DoCmdStopThreads()
        {
            AppModel.StopAllWork();
        }

        //NOTE Save all the modified mp3 files
        private void DoCmdSave()
        {
            AppModel.SaveCollection(View);                    
        }

        //NOTE Start the covers search
        private void DoCmdSearch()
        {                
           
            //start the internet search        
            AppModel.LogEntry("Connecting to " + AppModel.CoverSearcher.AddInName);

            if (AppModel.CoverSearcher.Initialize())
            {
                //clean the logging and everything else at each search
                AppModel.NotFoundMp3 = new List<Mp3File>();
                AppModel.CoverImageCache.Reset(); //to release memory, to change when I will store the image in a DB
                AppModel.CoverSearcher.ClearCache();

                List<Mp3File> selected = AppModel.SelectedSongs.ToList<Mp3File>();
                AppModel.CoverSearcher.Songs = selected;

                //display UI
                AppModel.ProgressOperationQueue.Add(AppModel.CoverSearcher);
                AppModel.StartProgressBarInternal(AppModel.ProgressOperationQueue.ToList<IProgressOperation>());

                //building the list of not found songs
                foreach (Mp3File m in AppModel.SelectedSongs)
                    if (m.ImageUrl == null)
                        AppModel.NotFoundMp3.Add(m);

                AppModel.ShowCoverPreviewWindow(); //display found covers

            }
            else
                MetroMessageBox.MetroShow(String.Empty, "Could not connect to the online database", true, App.MainView, MessageIcon.Error);
        }

        private void DoCmdOpenFLog()
        {
            App.Tracer.Flush();
            App.Tracer.Close();
            System.Diagnostics.Process.Start("notepad.exe", App.LogFileName);
        }

        private void DoCmdAbout()
        {
            AboutView aboutW = new AboutView(App.MainView);
            aboutW.ShowDialog();
        }
       
        public void DoCmdOpenFolder(DirectoryInfo dir)
        {
            if (dir != null)
                AppModel.ParentFolder = dir; //not null after a drag&drop

            //select new folder
            FolderExplorerView folderView = new FolderExplorerView();
            folderView.ShowDialog();
            if (folderView.DialogResult.Value){
                AppModel.LoadMp3FromFolders(); //only if the user changed the collection
                OnPropertyChanged("CurrentFolder"); //status bar update
            }
     
        }
        #endregion

        private bool CanExecuteSearch()
        {
            if (!AppModel.IsAppWorking && AppModel.SelectedSongs.Count > 0)
                return true;
            else
                return false;
        }     
    }
}